/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { h, resolveComponent } from 'vue'
// import { ConsoleLogger } from "@microsoft/signalr/dist/esm/Utils";
import modelHeader from './warehouse/ProductModelBody.vue'
import gridFooter from './warehouse/Ware_WareHouseGridFooter.vue'
import { chunkArray, getDatakey } from '@/uitils/utils'
let extension = {
  data() {
    return {
      unitList: [],
      inStoreTypeList: [],
    }
  },
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter,
    //新建、编辑弹出框扩展组件
    modelHeader,
    modelBody: {
      emits: ['parentCall'],
      render() {
        return [
          h(
            resolveComponent('el-alert'),
            {
              style: { 'margin-bottom': '5px' },
              'show-icon': true,
              type: 'warning',
              closable: false,
              title: '直接点击【入库数量】可以直接进行修改',
            },
            ''
          ),
        ]
      },
    },
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      this.single = true
      this.columnIndex = true
      //点击单元格编辑与结束编辑(默认是点击单元格编辑，鼠标离开结束编辑)
      this.detailOptions.clickEdit = true
      this.tableMaxHeight = (document.body.clientHeight - 260) / 2
      // this.buttons.splice(3,0,{  //也可以用push或者splice方法来修改buttons数组
      //   name: '打印', //按钮名称
      //   icon: 'el-icon-printer', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //   type: 'warning', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //   onClick: function () {
      //     let selectRow =   this.$refs.table.getSelected();
      //     if (selectRow.length == 0) {
      //       return this.$error('请选择要编辑的行!');
      //     }
      //     if (selectRow.length != 1) {
      //       return this.$error('只能选择一行数据进行编辑!');
      //     }
      //     let html = document.getElementById("collect");
      //     window.open(this.http.ipAddress + 'Print-Designer/print.html?cat=Ware_WareHouseBill&id=' + selectRow[0].WareHouseBill_Id  + "&token=" + this.$store.getters.getToken(),'_blank')
      //   }
      // });
      this.buttons.forEach((item) => {
        if (item.value == 'Audit') {
          item.onClick = async () => {
            // console.log(this.$refs.table.getSelected())
            let selectList = this.$refs.table.getSelected()
            if (selectList.length == 0)
              return this.$message.error('请选择要审核的单据')
            let { WareHouseBill_Id, WareHouseBillCode, Bstate } = selectList[0]
            if (Bstate !== 0) return this.$message.error('该单据已审核')
            let res = await this.http.post(
              `/api/Ware_WareHouseBill/InsertWareHouseRows?WareCode=${WareHouseBillCode}&WareId=${WareHouseBill_Id}`,
              null,
              true
            )
            if (res.status) {
              this.$message.success('审核成功')
              this.search()
            } else {
              this.$message.error(res.message)
            }
          }
        }
      })

      //这边不使用延迟函数会报错，猜测原因是异步请求堵塞了生命周期的执行
      this.$nextTick(() => {
        getDatakey(['unitList', 'inStoreType']).then((res) => {
          this.unitList = res[0].data
          this.inStoreTypeList = res[1].data
        })
      })

      let { permission } = this.$store.getters.getPermission(
        '/Ware_WareHouseBill'
      )
      if (permission.includes('print')) {
        this.buttons.push({
          name: '打 印',
          icon: 'el-icon-printer',
          type: 'warning',
          onClick: () => {
            let selectList = this.$refs.table.getSelected()
            if (selectList.length == 0)
              return this.$message.error('请选择要打印的单据')
            let rows = this.$refs.gridFooter.rows
            rows = rows.map((item) => {
              let unit = ''
              this.unitList.some((i) => {
                if (i.key == item.Unit_Id) {
                  unit = i.value
                  return true
                }
              })
              return {
                ...item,
                Unit_Id: unit,
              }
            })

            selectList = selectList.map((item) => {
              let type = ''
              this.inStoreTypeList.some((i) => {
                if (i.key == item.WareHouseBillType) {
                  type = i.value
                  return true
                }
              })
              return {
                ...item,
                WareHouseBillType: type,
              }
            })
            let data = {
              mainData: selectList[0],
              detailData: rows,
            }

            this.print(data)
          },
        })
      }

      this.columns.unshift({
        title: '操作',
        field: 'action',
        width: 150,
        render: (h, { row }) => {
          let dom1 = null
          if (permission.includes('Cancel')) {
            dom1 =
              row.Bstate == 0 ? (
                <el-link
                  underline={false}
                  type="primary"
                  onClick={() => this.handleCancel(row)}
                >
                  <i class="el-icon-folder-delete"></i>
                  作废
                </el-link>
              ) : null
          }

          return h('div', null, [dom1])
        },
      })

      this.editFormOptions.forEach((item) => {
        item.forEach((x) => {
          if (x.field == 'ProcureCode') {
            x.onChange = (value) => {
              this.getProcureMaterial('采购', value)
            }
          }

          if (x.field == 'MoCode') {
            x.onChange = (value) => {
              this.getProcureMaterial('委外采购', value)
            }
          }
        })
      })
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      //明细表选择数据源操作
      //获取明细表备注列，给备注列添加选择数据操作
      this.detailOptions.buttons.shift()
      this.detailOptions.buttons.unshift({
        name: '选择产品', //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        hidden: false, //是否隐藏按钮(如果想要隐藏按钮，在onInited方法中遍历buttons，设置hidden=true)
        onClick: function () {
          //触发事件
          if (!this.editFormFields.WareHouseBillType)
            return this.$message.error('请先选择入库类型')
          this.$refs.modelHeader.open(this.editFormFields.WareHouseBillType)
        },
      })
      this.detailOptions.columns.forEach((item) => {
        if (
          item.field == 'MaxInventory' ||
          item.field == 'MinInventory' ||
          item.field == 'SafeInventory' ||
          item.field == 'InventoryQty'
        ) {
          item.hidden = true
        }
      })
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      if (result.length > 0) {
        this.$nextTick(() => {
          this.$refs.gridFooter.rowClick(result[0], 'wareHouse')
        })
      }

      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      let flag = true
      let msg = ''
      // console.log(formData.mainData.WareHouseBillType)

      let WareHouseBillType = formData.mainData.WareHouseBillType
      if (WareHouseBillType == 'purchase') {
        if (this.editFormFields.ProcureCode == '') {
          flag = false
          msg = '请填写关联的采购订单'
        }

        formData.detailData.some((item) => {
          let ProductType = item.ProductCode.substr(0, 2).toUpperCase()
          console.log(ProductType)
          if (ProductType !== 'FE' && ProductType !== 'AM') {
            flag = false
            msg = `采购入库只能入库原材料或者半成品,请确认选择的产品类型是否为原材料或者半成品！`
            return true
          }
        })
      } else if (WareHouseBillType == 'outsource') {
        formData.detailData.some((item) => {
          let ProductType = item.ProductCode.substr(0, 2).toUpperCase()
          if (ProductType !== 'FE' && ProductType !== 'FP') {
            flag = false
            msg = `委外入库只能入库原材料或者产成品,请确认选择的产品类型是否为原材料或者产成品！`
            return true
          }
        })
      } else if (WareHouseBillType == 'customerreturn') {
        formData.detailData.some((item) => {
          let ProductType = item.ProductCode.substr(0, 2).toUpperCase()
          if (ProductType !== 'FP') {
            flag = false
            msg = '客退入库只能入库产成品,请确认选择的产品类型是否为产成品！'
            return true
          }
        })
      } else if (
        WareHouseBillType == 'SectionMateriel' ||
        WareHouseBillType == 'SpecialMateriel'
      ) {
        formData.detailData.some((item) => {
          let ProductType = item.ProductCode.substr(0, 2).toUpperCase()
          if (ProductType !== 'FE' && ProductType !== 'AM') {
            flag = false
            msg =
              '部分收料和特料特采只能入库原材料和包辅材,请确认选择的产品类型是否为原材料或者包辅材！'
            return true
          }
        })
      }
      // else if (WareHouseBillType == 'other') {
      //   formData.detailData.some((item) => {
      //     let ProductType = item.ProductCode.substr(0, 2).toUpperCase()
      //     if (ProductType !== 'FE' && ProductType !== 'AM' && ProductType !== 'SFP') {
      //       flag = false
      //       msg = '其他入库只能入库原材和半成品,请确认选择的产品类型是否为原材和半成品！'
      //       return true
      //     }
      //   })
      // }

      formData.mainData.Bstate = 0
      // console.log(this.editFormFields);

      if (flag) return true
      else {
        this.$message.error(msg)
        return false
      }
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row) //单击行时选中当前行;
      //调用Doc_Order1GridFooter.vue文件中(订单明细)的查询
      this.$refs.gridFooter.rowClick(row)
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      this.editFormOptions.forEach((item) => {
        item.forEach((x) => {
          //如果是编辑设置为只读
          if (x.field == 'WareHouseBillCode') {
            //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
            //vue3版本改为设置：x.disabled=isEDIT
            x.placeholder = '请输入，忽略将自动生成'
          }
        })
      })

      if (this.currentAction == 'update') {
        this.boxButtons.forEach((item) => {
          if (item.value == 'save') {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons.forEach((item) => {
          if (item.value == 'save') {
            item.hidden = false
          }
        })
      }

      this.$refs.detail.changeTotal(0)
    },
    async handleCancel(row) {
      let res = await this.http.post(
        `/api/Ware_WareHouseBill/WareHouseRowsCancellation?WareHouseID=${row.WareHouseBill_Id}`,
        null,
        true
      )

      if (res.status) {
        this.$message.success(res.message)
        this.search()
      } else {
        this.$message.error(res.message)
      }
    },
    async getProcureMaterial(type, value) {
      if (value !== '') {
        const types = type == '采购' ? 0 : 1
        const res = await this.http.post(
          `/api/Ware_WareHouseBill/Warehouselect?code=${value}&type=${types}`,
          null,
          true
        )
        // console.log(res)
        if (res.data == null) {
          this.$message.error(res.message)
          this.$refs.detail.rowData = []
        } else {
          const arr = res.data.map((item) => {
            return {
              ProductCode: item.productCode,
              ProductName: item.productName,
              InStoreQty: item.inQnty,
              ProductStandard: item.invStandard,
              WareHouseBillType: item.productType,
              Unit_Id: item.unit_Id,
            }
          })
          // console.log(this.$refs.detail);

          this.$refs.detail.rowData = arr
        }
      }
    },
    print({ mainData, detailData }) {
      console.log(mainData)
      console.log(detailData)
      let printWindow = window.open('', '_blank')
      let {
        WareHouseBillCode,
        WareHouseBillType,
        ProcureCode,
        WareHouseDate,
        Creator,
        Bstate,
      } = mainData
      printWindow.document.open()
      let style = `<style>
                      .title {
                        text-align:center;
                        position: relative;
                        margin: 5px 0;
                      }

                      .header {
                        display: flex;
                        font-size: 14px;
                      }

                      .t_head {
                        flex: 1;
                        display: flex;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                        flex-direction: column;
                        flex: 1;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex; 
                        justify-content: center;
                      }

                      .th_title .th_title_space {
                        display: flex; 
                        flex: 1;
                        flex-direction: column;
                        justify-content: flex-end;
                      }

                      .label {
                        display: flex;
                        align-items: flex-end;
                        text-align: left;
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                        font-size: 12px;
                      }

                      .grid_table tr,.grid_table tr td{
                        border: 1px dotted black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: space-between; 
                        list-style: none;
                        font-size: 12px;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .cb {
                        margin-left: 20px;
                        text-align: left;
                      }
                    </style>`
      let title = `<div>
                        <h2 class="title">昆山鸿永峻精密五金电子科技有限公司</h2>
                        <h3 class="title">入库单</h3>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> 入库单号: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${WareHouseBillCode}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 采购单号: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${
                                ProcureCode == null ? '' : ProcureCode
                              }</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 入库类型: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${WareHouseBillType}</span>
                            </li>
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                            <span class="label"> 入库时间: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${WareHouseDate}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 创&nbsp;&nbsp;建&nbsp;&nbsp;人: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${Creator}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${
                                Bstate == 1 ? '已审批' : '未审批'
                              }</span>
                            </li>
                          </ul>
                        </div>
                    </div>`
      let footer = `<div>
                    <ul class="footer"> 
                      <li>
                        核准
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        入库员
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        仓管
                        <span class="footer_space"></span>
                      </li>
                    </ul>
                  <div>`
      let table = ''
      let result = chunkArray(detailData, 24)
      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          main += `<tr>
            <td>${index + 1}</td>
            <td>${item.ProductName}</td>
            <td>${item.ProductCode}</td>
            <td>${item.ProductStandard}</td>
            <td>${item.Unit_Id}</td>
            <td>${item.InStoreQty}</td>
            <td></td>
          </tr>`
        })

        table += `
        <table class="grid_table">
          <thead>
            <tr>
              <th style="width: 50px;">序号</th>
              <th>物料名称</th>
              <th>物料编码</th>
              <th>规格</th>
              <th>单位</th>
              <th>入库数量</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${main}
          </tbody>
        </table>${footer}`
      })

      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(table)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
